package com.xiao.login.vm.state

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer

/**
 * 非粘性事件
 * 与RxJava的PublishSubject相同
 */
class LiveEvent<T>:LiveData<T>() {
    private val observerWrappers = mutableMapOf<Observer<*>, ObserverWrapper<T>>()
    private var pending:Boolean = false
    private class ObserverWrapper<T>(
        private val observer: Observer<in T>,
        private val pending:()-> Boolean
    ) : Observer<T> {
        override fun onChanged(t: T) {
            // false 为历史值
            if (pending()) {
                observer.onChanged(t)
            }
        }
    }


    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        observerWrappers[observer]?.let {
            return
        }
        val observerWrapper = ObserverWrapper<T>(observer){pending}
        observerWrappers[observer] = observerWrapper
        super.observe(owner, observerWrapper)
    }

    public override fun removeObserver(observer: Observer<in T>) {
        val observerWrapper = observerWrappers.remove(observer);
        if (observerWrapper != null) {
            super.removeObserver(observer)
        }
    }

    public override fun setValue(value: T) {
        pending = true
        super.setValue(value)
        pending = false
    }


}